package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import model.TypeModel;

public class Type {
	
	public Type() {}

	public List<TypeModel> ListType() {
		List<TypeModel> list = new ArrayList<TypeModel>();
		Connection con = new Connect().getConnection();
		String sql = "SELECT * FROM TYPE ORDER BY ID DESC";
		try {
			PreparedStatement state = con.prepareStatement(sql);
			ResultSet rs = state.executeQuery();
			while (rs.next()) {
				list.add(new TypeModel(
						rs.getString("id"),
						rs.getString("name")));
			}
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public boolean UpdateType(TypeModel t) {
		Connection con = new Connect().getConnection();
		String sql = "UPDATE TYPE SET ID = '" + t.getId()+ "', NAME = '"+ t.getName()+"'";
		try {
			PreparedStatement state = con.prepareStatement(sql);
			state.executeUpdate();
			con.close();
			return true;
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		return false;
	}

	public void DeleteType(String id) {
		Connection con = new Connect().getConnection();
		String sql = "DELETE FROM TYPE WHERE ID = '" + id + "'";
		try {
			PreparedStatement state = con.prepareStatement(sql);
			state.executeUpdate();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public boolean CreateType(TypeModel t) {
		Connection con = new Connect().getConnection();
		String sql = "INSERT INTO TYPE VALUES('" + t.getId()+ "', '" + t.getName()+"')";
		try {
			PreparedStatement state = con.prepareStatement(sql);
			state.executeUpdate();
			con.close();
			return true;
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		return false;
	}

	public boolean CheckExistType(String id) {
		Connection con = new Connect().getConnection();
		String sql = "SELECT ID FROM TYPE WHERE ID = '" +id 
				+ "'";
		try {
			PreparedStatement state = con.prepareStatement(sql);
			ResultSet rs = state.executeQuery();
			if (rs.next())
				return true;
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}


}
